<?php
/**
 * Copyright (c) 2018. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/**
 * Created by PhpStorm.
 * User: 我型我素
 * Date: 2017/5/8
 * Time: 19:16
 */

namespace SDXApi\Controller;


use Think\Controller;
use Common\Api\Ali_ossApi;
use Think\Log;


/*
第三方订单状态标识
0 默认未处理订单
1 配送中
2 已撤销  待回仓
3 修改配送时间 待回仓
4 已撤销 已回仓
5 修改配送时间 已回仓
6 已送达
7 待回仓
8 已回仓
*/
class SdxshippingController extends Controller{

    protected $sdx_bsc_config;
    protected $store_id = 0;
    protected $store_user_id = 0;
    protected $data = array();
    protected $server_url = "";
    protected $client_store_no = '';
    protected $app_secret = "";
    protected $app_key = "";

    protected function _initialize() {
        $this->sdx_bsc_config = C('SDX_BSC_CONFIG');
        $this->server_url = $this->sdx_bsc_config['SERVER_URL'];
        $this->client_store_no = $this->sdx_bsc_config['CLIENT_STORE_NO'];
        $this->app_secret = $this->sdx_bsc_config['APP_SECRET'];
        $this->app_key = $this->sdx_bsc_config['APP_KEY'];

        $client_time = time();
        $client_sign_method = "sha1";
        $old_sign = $this->client_store_no.$client_time.$client_sign_method.$this->app_secret.substr($client_time, -1);
        $data['sign'] = strtoupper(sha1($old_sign));
        $data['time'] = $client_time;
        $data['store_no'] = $this->client_store_no;
        $data['sign_method'] = $client_sign_method;
        $data['app_key'] = $this->app_key;

        $this->data = $data;
    }

    public function write_log($message,$filename){
        $log = new Log();
        $destination = C('LOG_PATH').date('y_m_d').'_'.$filename.'.log';

        $log->write($message,'DEBUG','',$destination);
    }

    //* @param $contact
    //* @param $phone
    //* @param $store_id
    //* @param $third_sn
    //* @param $op_type 1:[开始配送] 2:[完成配送] 3:[已到站] 4:[需回仓]
    //                  5:[延迟订单] 6:[配送订单] 7:[问题单] 8 司机揽件
    //                  9返回揽件 10反仓确认 11周边撤单  12取消回仓
    //* @param $time
    //* @param $text
    //* @param $best_time
    /**
     *订单状态回调
     *
     *order_sn contact phone op_time remark
     */
    public function order_notify(){
        $data_json = str_replace('&quot;','"',I("post.data"));
        $this->write_log($data_json,'bsc_order_notify');

        $notify = json_decode($data_json, true);

        $_POST['store'] = 1;

        $sign =strtoupper(md5($this->app_secret.$this->app_key.$this->client_store_no.$notify['order_sn'].$notify['op_type'].$notify['op_time'].substr($notify['op_time'], -1)));
        if($sign==$notify['sign']){
            switch($_SERVER['SERVER_NAME']){
                case 'api.xian3.com':
                    $this_url='xian3.com';
                break;
                case 'api.test.shidexian.com':
                    $this_url='test.shidexian.com';
                break;
                case 'api.shidexian.com':
                    $this_url='w.shidexian.com';
                break;
                default:
                    $this_url='w.shidexian.com';
                break;
            }

            $list = M("order_info")->where(array("order_sn"=>$notify['order_sn']))
                ->field("wid,pay_status,shipping_status,order_status,
                surplus,money_paid,order_amount,best_time_start,
                best_time,consignee,order_sn,mobile,user_id,order_id")->find();
            if(empty($list)){
                $this->write_log("未找到此订单号：".$notify['order_sn'],'order_notify');
                return false;
            }

            $user_id_list = C('sdx_peisong_user_id');
            $user_id = $user_id_list[$list['wid']];

            $wechat_param=array();
            switch ($notify['op_type']){
                case 1:
                    //开始配送
                    $data_save['order_status']=5;
                    $data_save['shipping_status']=1;
                    $data_save['shipping_time']=gmtime();
                    $data_save['wp_userid'] = 99999;
                    $data_save['station'] = 2; //开始配送 修改到站状态为已出站
                    $data_save['shipping_exman_name'] = $notify['contact']; //
                    $data_save['shipping_exman_mobile'] = $notify['phone']; //
                    $data_save['shipping_extend_status'] = $this->get_shipping_extend_status($notify['op_type']);    //第三方订单操作状态
                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,1,$list['pay_status'],"开始配送",1,$user_id);
                        $this->record_logistics($list['order_id'],1,"订单已由:".$notify['contact']."「 ".$notify['phone']." 」开始配送");
                    }
                    $datetime = date("Y-m-d",$list['best_time_start']);
                    $remark['best_time'] = $datetime.' '.date("H:i:s",$list['best_time_start']).'-'.date("H:i:s",$list['best_time']);
                    $remark['code'] = A("Distribution")->get_order_receipt_code($list['order_id']);
                    $oid=$list['user_id'];
                    $Code=md5($oid.'sdx@9999');
                    $goods_name=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->limit(1)->getField("goods_name");
                    $goods_number=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->count();
                    $wechat_param['url']="https://".$this_url."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$list['order_id']."&utm_source=GZHshipping_start_notice";
                    $wechat_param['first']='尊敬的'.$list['consignee'].'，您所订购的'.$goods_name.'等'.$goods_number.'件商品已经在配送中，预计到达时间为'.$remark['best_time'].'，请保持手机畅通。';
                    $wechat_param['keyword1']=$list['order_sn'];
                    $wechat_param['keyword2']=$notify['contact'];
                    $wechat_param['keyword3']=$notify['phone'];
                    $wechat_param['remark']=array("您的订单收货码为：[ ".$remark['code']." ],确认收货时请将此码提供给配送员。如代收，请把该码提供给代收人","#FF0000");
                    A("Smsapi")->send_message_api('receipt_verification',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],$remark,'',$wechat_param);

                break;
                case 2:
                    //处理库存
                    $is_shipping_status = M("order_action")->where(array("order_id"=>$list['order_id'],"shipping_status"=>2))->count();
                    if(empty($is_shipping_status)){
                        A("Distribution")->order_buckle_inventory($list);
                        $dk_msg = " 处理库存";
                    }else{
                        $dk_msg = " 未处理库存";
                    }

                    //完成配送
                    $data_save['order_status']=5;
                    $data_save['shipping_status']=2;
                    $data_save['confirm_time']=gmtime();
                    $data_save['wp_userid']=99999;
                    $data_save['shipping_extend_status'] = $this->get_shipping_extend_status($notify['op_type']);    //第三方订单操作状态
                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,2,$list['pay_status'],"配送完成".$dk_msg,1,$user_id);
                        $this->record_logistics($list['order_id'],2,"配送完成");
                    }

                    $oid=$list['user_id'];
                    $Code=md5($oid.'sdx@9999');
                    $goods_name=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->limit(1)->getField("goods_name");
                    $goods_number=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->count();
                    $louxiaoer_info=A("Smsapi")->get_louxiaoer_info($list['order_id']);
                    if(!empty($louxiaoer_info['name']) && !empty($louxiaoer_info['phone'])){
                        $housekeeper="微信添加楼管家".$louxiaoer_info['name']."-".$louxiaoer_info['phone']."还能最高返8元。祝生活愉快！";
                    }else{
                        $housekeeper="联系楼管家还能再返现。如需添加，请于微信公众号留言。";
                    }
                    $wechat_param['url']="https://".$this_url."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$list['order_id']."&utm_source=GZHorder_finish";
                    $wechat_param['first']='尊敬的'.$list['consignee'].',您所订购的'.$goods_name.'等'.$goods_number.'件商品已经成功送达';
                    $wechat_param['keyword1']=$list['order_sn'];
                    $wechat_param['keyword2']=sprintf("%.2f",($list['order_amount']+$list['money_paid']+$list['surplus']));
                    $wechat_param['keyword3']=date("Y-m-d H:i:s");
                    $wechat_param['remark']=$housekeeper;
                    A("Smsapi")->send_message_api('order_finish',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],array(),'',$wechat_param);
                    //确认收货，赠送红包
                    D('Userbonus')->send_bonus_to_user($list['user_id'],$list['order_id']);
                break;
                case 3:
                    //已到站
                    $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"已到达物流点",1,$user_id);
                break;
                case 4:
                    //需回仓
                    $data_save['order_status']=5;
                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;
                    $data_save['station'] = 3;
                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"需回仓//".$notify['text'],1,$user_id);
                    }
                break;
                case 5:
                    //延迟订单
                    $shipping_arrive_time = explode(',', $notify['best_time']);
                    $data_save['best_time_start'] = $shipping_arrive_time[0];
                    $data_save['best_time'] = $shipping_arrive_time[1];

                    //$diff_time = round(($data_save['best_time_start']-$list['best_time_start'])/3600/24);

                    $data_save['order_status']=5;
                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;
                    $huic_test ="";

                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"延迟订单//".$notify['remark'].$huic_test,1,$user_id);
                    }
                    $best_time = explode(",",$notify['best_time']);
                    $datetime = date("Y-m-d",$best_time[0]);
                    $smsremark['best_time'] = $datetime.' '.date("H:i:s",$best_time[0]).'-'.date("H:i:s",$best_time[1]);
                    $smsremark['action'] = $notify['text'].$huic_test;

                    $code=md5($list['user_id'].'sdx@9999');
                    $wechat_param=array();
                    $wechat_param['url']='https://'.$this_url.'/?index&sid='.$list['user_id'].'&code='.$code.'&lll=#!/reted?ordId='.$list['order_sn'];
                    $wechat_param['keyword1']=$list['order_sn'];
                    $wechat_param['keyword2']=$notify['text'];
                    $wechat_param['keyword3']="[".date('Y-m-d H:i:s',$list['best_time_start'])."] - [".date('Y-m-d H:i:s',$list['best_time'])."]";
                    $wechat_param['keyword4']="[".date('Y-m-d H:i:s',$best_time[0])."] - [".date('Y-m-d H:i:s',$best_time[1])."]";
                    A("Smsapi")->send_message_api('delayed_order',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],$smsremark,null,$wechat_param);
                break;
                case 6:
                    //配送退单
                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;

                    M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);

                    $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"配送员退单",1,$user_id);
                break;
                case 7:
                    //问题订单
                    $shipping_arrive_time = explode('-', $notify['best_time']);
                    $data_save['best_time_start'] = $shipping_arrive_time[0];
                    $data_save['best_time'] = $shipping_arrive_time[1];


                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;
                    $data_save['station'] = 1;
                    $data_save['action_type'] = 6; //问题单日志

                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"问题订单//".$notify['remark'],1,$user_id);
                    }
                    $datetime = date("Y-m-d",$data_save['best_time_start']);
                    $smsremark['best_time'] = $datetime.' '.date("H:i:s",$data_save['best_time_start']).'-'.date("H:i:s",$data_save['best_time']);
                    $smsremark['action'] = " [ ".$notify['text']." ] ";
                    A("Smsapi")->send_message_api('question_order',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],$smsremark);

                break;
                case 8:
                    //司机派送揽件
                    $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"干线派送揽件",1,$user_id);
                    $this->record_logistics($list['order_id'],5,"干线派送揽件");
                break;
                case 9:
                    //司机回仓揽件
                    $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"干线回仓揽件",1,$user_id);
                break;
                case 10:
                    //司机回仓确认
                    //改订单为需回仓
                    $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                    $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"回仓确认",1,$user_id);
                    $data_save['outgo'] = 2;
                    $data_save['shipping_extend_status'] = $this->get_shipping_extend_status($notify['op_type']);    //第三方订单操作状态
                    M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                break;
                case 11:
                    //周边撤单
                    $data_save['shipping_status']=5;
                    $data_save['wp_userid'] = 0;
                    $data_save['station'] = 1;

                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"周边撤单",1,$user_id);
                    }
                break;
                case 12:
                    //取消回仓
                    $data_save['outgo'] = 1;             //已出仓
                    $data_save['station'] = 1;           //已回仓
                    $data_save['shipping_status'] = 5;   //配货完成
                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"取消回仓",1,$user_id);
                    }
                break;
                case 13:
                    //配送员接单
                    $data_save['shipping_extend_type'] = 'sdx';
                    $data_save['shipping_exman_name'] = $notify['contact'];
                    $data_save['shipping_exman_mobile'] = $notify['phone'];
                    $id=M('order_info')->where(array("order_id"=>$list['order_id']))->save($data_save);
                    if($id!=false){
                        $user_name= "SDX_BSC_NOTIFY->".$notify['contact']."「 ".$notify['phone']." 」";
                        $this->write_order_action($user_name,$list['order_id'],5,5,$list['pay_status'],"已有配送员接单",1,$user_id);
                    }
                break;
                default:
                    $this->write_log("未找到此方式：".$notify['op_type'],'order_notify');
            }
        }else{
            $this->write_log("校验失败:".$data_json."///".$notify['sign'],'order_notify');
        }
        echo "success";

    }

    /**
     * @param $status
     * @return int
     */
    private function get_shipping_extend_status($status){
        switch ($status){
            case '1':
                $shipping_extend_status=1;   //配送中
            break;
            case '2':
                $shipping_extend_status=6;   //已送达
            break;
            case '10':
                $shipping_extend_status=7;  //待回仓
            break;
            default:
                $shipping_extend_status=0;
            break;
        }

        return $shipping_extend_status;
    }

    /**
     * 订单操作记录
     * @param $user         //操作人描述
     * @param $id           //订单ID
     * @param $order        //订单状态
     * @param $shipping     //配送状态
     * @param $pay          //支付状态
     * @param $note         //操作备注
     * @param $to_user         //1 显示到用户
     */
    public function write_order_action($user, $id, $order, $shipping, $pay, $note,$to_user=0,$user_id=1){
        $data['action_user']=$user;
        $data['order_id']=$id;
        $data['order_status']=$order;
        $data['shipping_status']=$shipping;
        $data['pay_status']=$pay;
        $data['action_note']=$note;
        $data['log_time']=gmtime();
        $data['user_id']=$user_id;
        $data['to_user']=$to_user;
        M('order_action')->add($data);
    }

    /**
     * 写入订单物流信息
     * @param $order_id
     * @param $shipping_status
     * @param $remark
     */
    public function record_logistics($order_id, $shipping_status, $remark){
        $data['log_time']=gmtime();
        $data['remark']=$remark;
        $data['shipping_status']=$shipping_status;
        $data['order_id']=$order_id;
        M('logistics')->add($data);
    }

}